<?php

class GenericBlocks {

	private $_userID;
	private $_userdir;
	private $_pagesdir;
	private $_thumbsdir;
	private $_thumbwidth;
	private $_db;
	private $_num_pages;


	public function __construct($db=NULL) {
		ini_set('post_max_size', '64M');
		ini_set('upload_max_filesize', '64M');
		$this->_userID = $_SESSION['UserID'];
		$this->_userdir = $_SESSION['home_dir'];
		$this->_pagesdir = "/pages/";
		$this->_thumbsdir = "/thumbs/";
		$this->_thumbwidth = 250;
		$this->_num_pages = 0;
		if(is_object($db))
        {
            $this->_db = $db;
        }
        else
        {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
            $this->_db = new PDO($dsn, DB_USER, DB_PASS);
        }
		
	
}

public function getMyBlocks() {
	$sql = "Select BlocksThumb, BlocksName, blocks_dir
			FROM blocks
			WHERE users_UserID = :user
			Order By BlocksID Desc;";
	if($stmt = $this->_db->prepare($sql)) {
		$stmt->bindParam(":user", $_SESSION['ID'], PDO::PARAM_INT);
		$stmt->execute();
		while($row = $stmt->fetch()) {
			echo '<li><img src=\''. $row['blocks_dir']."/". $row['BlocksThumb'] .'\' alt=\''. $row['BlocksName']. '\' title=\''. $row['BlocksName'].'\' /></li>';
		}
		$stmt->closeCursor();
	}

}

public function getRecentTile() {
	$sql = "Select BlocksName, blocks_dir
			FROM blocks
			WHERE users_UserID = :user
			Order By BlocksID Desc
			LIMIT 1;";
	if($stmt = $this->_db->prepare($sql)) {
		$stmt->bindParam(":user", $_SESSION['ID'], PDO::PARAM_INT);
		$stmt->execute();
		
		
		while($row = $stmt->fetch()) {
		
			$cover = 'cover.jpg';
			echo '<h1>'. $row['BlocksName'] .'</h1><img src=\''. $row['blocks_dir'] .'/'. $cover .'\'/>';
		}
		$stmt->closeCursor();
	}


}



public function deleteBlocks() {
	$blocksname = $_POST['name'];
	$blocksdirname = preg_replace('/\s+/', '_', $blocksname);
	$blocksdirname = str_replace(':', '_', $blocksdirname);
	$blocksdirname = str_replace('#', '', $blocksdirname);
	$blocksdir = $this->_userdir ."/blocks/". $blocksdirname;
	
	$sql = "Delete from blocks
	WHERE BlocksName =:name AND users_UserID =:userID";
	
	if($stmt = $this->_db->prepare($sql))
	{
	  $stmt->bindParam(':name',$blocksname, PDO::PARAM_STR);
	  $stmt->bindParam(':userID', $_SESSION['ID'], PDO::PARAM_INT);
	  $stmt->execute();
	  $stmt->closeCursor();
	
	  $this->rrmdir($blocksdir);
	}
}

/* Main function for creating new blocs */
public function createNewBlocks() {
	/* Create a new folders for the new blocks */
	$blocksname = $_POST['name'];
	$blockssynopsis = $_POST['synopsis'];
	$blocksdirname = preg_replace('/\s+/', '_', $blocksname);
	$blocksdirname = str_replace(':', '_', $blocksdirname);
	$blocksdirname = str_replace('#', '', $blocksdirname);
	$blocksdir = $this->_userdir ."/blocks/". $blocksdirname;
	if(!file_exists($blocksdir)) {  
      if(!mkdir($blocksdir)) {  
           die("There was a problem. Please try again!");  
      }   
       }  
	   
	$this->_pagesdir = $blocksdir ."/pages/";
	$this->_thumbsdir = $blocksdir ."/thumbs/";
	
	if(!file_exists($this->_thumbsdir)) {  
      if(!mkdir($this->_thumbsdir)) {  
           die("There was a problem. Please try again!");  
      }   
       }
	if(!file_exists($this->_pagesdir)) {  
      if(!mkdir($this->_pagesdir)) {  
           die("There was a problem. Please try again!");  
      }   
       }
	$thumb_name = $this->uploadFiles($blocksdirname, $blocksdir);
	$this->rrmdir($this->_userdir ."/blocks/tmp");
	
	
	$this->insertBlocksDB($blocksname,$blocksdirname, $blockssynopsis, $blocksdir, $thumb_name);
	
	echo '<li><img src=\''. $blocksdir."/".$thumb_name .'\' alt=\''. $blocksname . '\' title=\''. $blocksname.'\' /></li>';
	
	

}

private function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") $this->rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }

/* Insert new blocks into database*/
private function insertBlocksDB($name,$blocksdirname, $synopsis, $blocksdir, $thumb_name) {
	$date = date("Y-m-d");
	$sql = "INSERT INTO blocks(BlocksName, blocksdir_name, Summary,published, pages, BlocksThumb, blocks_dir, users_UserID)
			VALUES(:name, :dirname, :sum, :pub, :pages, :thumb, :dir, :user)";
	if($stmt = $this->_db->prepare($sql)) {
		$stmt->bindParam(":name", $name, PDO::PARAM_STR);
		$stmt->bindParam(":dirname", $blocksdirname, PDO::PARAM_STR);
		$stmt->bindParam(":thumb", $thumb_name, PDO::PARAM_STR);
		$stmt->bindParam(":dir", $blocksdir, PDO::PARAM_STR);
		$stmt->bindParam(":user", $_SESSION['ID'], PDO::PARAM_INT);
		$stmt->bindParam(":sum", $synopsis, PDO::PARAM_STR);
		$stmt->bindParam(":pub", $date, PDO::PARAM_STR);
		$stmt->bindParam(":pages", $this->_num_pages, PDO::PARAM_INT);
		$stmt->execute();
		
        $stmt->closeCursor();
			
	}
	else
		echo "Failed to insert new blocks into db!";
	
	

}



/*Uploads the files to the user dir*/
private function uploadFiles($blocksname, $blocksdir) {
	$files = array(); 
	$directory = opendir($this->_userdir ."/blocks/tmp");
	$blocksdir = $this->_userdir ."/blocks/". $blocksname;
	while($item = readdir($directory)){
		if ($item != '.' && $item != '..')
			$files[] = $item; 
	}
	$file_ary = $files;
	$first = true;
    foreach ($file_ary as $file) {
        $tmpfilePath = $this->_userdir ."/blocks/tmp/". $file;
		$this->_num_pages++;
		if($tmpfilePath != "") {
		$newfilePath = $this->_pagesdir ."". $file;
		copy($tmpfilePath, $newfilePath);
		$this->createThumbnail($file,$this->_thumbsdir, $file);
		//If first create thumbnail
		if($first) {
		 /* Create block thumb and cover */
		if(preg_match('/[.](jpg)$/', $file)) {  
			$thumb_name = $blocksname .".jpg";  
		} else if (preg_match('/[.](gif)$/', $filename)) {  
        $thumb_name = $blocksname .".gif";  
		} else if (preg_match('/[.](png)$/', $filename)) {  
         $thumb_name = $blocksname .".png";  
		}  
		 $this->createThumbnail($file,$blocksdir ."/",  $thumb_name);
		 $this->createCover($newfilePath, $blocksdir ."/");
		 $first = false;
		}
		}
		
	}

	return $thumb_name;
}


/*Creates thumbnail for the uploaded file*/

private function createThumbnail($filename, $thumbdir, $thumbname) {
      
    if(preg_match('/[.](jpg)$/', $filename)) {  
        $im = imagecreatefromjpeg($this->_pagesdir . $filename);  
    } else if (preg_match('/[.](gif)$/', $filename)) {  
        $im = imagecreatefromgif($this->_pagesdir . $filename);  
    } else if (preg_match('/[.](png)$/', $filename)) {  
        $im = imagecreatefrompng($this->_pagesdir . $filename);  
    }  
      
    $ox = imagesx($im);  
    $oy = imagesy($im);  
      
    $nx = $this->_thumbwidth;  
    $ny = floor($oy * ($this->_thumbwidth / $ox));  
      
    $nm = imagecreatetruecolor($nx, $ny);  
      
    imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);  
    imagejpeg($nm, $thumbdir . $thumbname);  
   

}

private function createCover($filename , $dir) {
    $newfilePath = $dir ."cover.jpg";
	copy($filename, $newfilePath);
   

}


/* Returns an easier managable array of the files */
private function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}





}



?>